﻿using Cms.Core.Application.IService.UserInfo;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Cms.Core.Application.IService.RoleInfo;
using System.Linq;
using Cms.Core.Application.Secutiry.Token;
using Cms.Core.Infrastructure.AuthHelper;

namespace Cms.Core.Application.Secutiry
{
    /// <summary>
    /// 在线用户信息提供者
    /// </summary>
    public class OnlineUserProvider:IOnlineUserProvider
    {

        /// <summary>
        /// 创建在线用户信息
        /// </summary>
        /// <param name="provider">服务提供器</param>
        /// <param name="userName">用户名</param>
        /// <returns>在线用户信息</returns>
        public virtual async Task<OnlineUser> Create(IServiceProvider provider, string userName)
        {
            var userService = provider.GetService<IUserService>();
        
            var userDto = await userService.FindUserByNameAsync(userName);
            if (userDto == null)
            {
                return null;
            }

            var roleService = provider.GetService<IRoleService>();
            var roles= await roleService.GetUserRolesByUserIdAsync(userDto.Id);
          
            bool isAdmin = roles.Any(o=>o.IsAdmin);
            //var permissionRequirement = provider.GetService<PermissionRequirement>();
            return new OnlineUser()
            {
                Id = userDto.Id,
                UserName = userDto.AccountNumber,
                NickName = userDto.UserName,

                IsAdmin = isAdmin,
                Roles = roles.Select(o => o.Name),
                //OnlineToken = new OnlineToken() { ExpirationTime=exp,Token=token,RefreshTime=exp.AddMinutes(permissionRequirement.RefreshCoefficients) }
            };
        }
    }
}
